package function;

import java.util.ArrayList;

public class Multiply extends Function {
	ArrayList<Function> functions;

	public Multiply(ArrayList<Function> f) {
		functions = new ArrayList<Function>();
		for (int i = 0; i < f.size(); i++) {
			if ((f.get(i) instanceof Constant)) {
				if (((Constant) f.get(i)).getConstant() != 0) {
					if (((Constant) f.get(i)).getConstant() != 1)
						functions.add(f.get(i));
				}
			} else
				functions.add(f.get(i));
		}
		if (functions.size() == 0)
			functions.add(new Constant(0));
	}

	public Multiply(Function f1, Function f2) {
		functions = new ArrayList<Function>();
		if ((f1 instanceof Constant)) {
			if (((Constant) f1).getConstant() != 0) {
				if (((Constant) f1).getConstant() != 1)
					functions.add(f1);
			}
		} else
			functions.add(f1);
		
		if ((f2 instanceof Constant)) {
			if (((Constant) f2).getConstant() != 0) {
				if (((Constant) f2).getConstant() != 1)
					functions.add(f2);
			}
		} else
			functions.add(f2);
		// if ((f1 instanceof Constant && ((Constant) f1).getConstant() != 0)
		// || (f2 instanceof Constant && ((Constant) f2).getConstant() != 0)) {
		// if (f1 instanceof Constant) {
		// if (((Constant) f1).getConstant() != 1)
		// functions.add(f1);
		// } else
		// functions.add(f1);
		// if (f2 instanceof Constant) {
		// if (((Constant) f2).getConstant() != 1)
		// functions.add(f2);
		// } else
		// functions.add(f2);
		// }
		if (functions.size() == 0)
			functions.add(new Constant(0));

	}

	public ArrayList<Function> getFunctions() {
		return functions;
	}

	public void setFunctions(ArrayList<Function> functions) {
		this.functions = functions;
	}

	public double evaluate(double x) {
		double sum = 1;
		for (int i = 0; i < functions.size(); i++)
			sum *= functions.get(i).evaluate(x);
		return sum;
	}

	public Function differentiate() {
		ArrayList<Function> result = new ArrayList<Function>();
		for (int i = 0; i < functions.size(); i++) {
			ArrayList<Function> term = new ArrayList<Function>();
			if (!(functions.get(i) instanceof Constant)) {
				term.add(functions.get(i).differentiate());
				for (int j = 0; j < functions.size(); j++) {
					if (i != j)
						term.add(functions.get(j));
				}
				result.add(new Multiply(term));
			}
		}
		if (result.size() == 0)
			result.add(new Constant(0));
		return new ADD(result);
	}

	public String toString() {
		String s = "";
		for (int i = 0; i < functions.size() - 1; i++)
			s += functions.get(i).toString() + " * ";
		s += functions.get(functions.size() - 1).toString();
		return s;
	}
}
